package com.ibm.crl.sb.thread.czbk;

/**
 * 
 * @author Super尚
 * 
 *         1.总共循环50次
 * 
 *         2.主线程循环100次
 * 
 *         3.子线程循环10次
 * 
 *         4.两个线程一次循环
 * 
 */
public class TraditionalCommunication {

	public TraditionalCommunication() {
		final Bussiness bussiness = new Bussiness();

		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					bussiness.sub(i);
				}
			}

		});
		thread.start();
		for (int i = 0; i < 50; i++) {
			bussiness.main(i);
		}
	}

	public static void main(String[] args) {
		new TraditionalCommunication();
	}

	class Bussiness {
		boolean isTrue = true;

		public synchronized void sub(int i) {
			while (!isTrue) {//精髓 不能用if 假唤醒 wait 帮助文档
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			for (int j = 0; j < 10; j++) {
				System.out.println("this is subthread:" + j + "loop of:" + i);
			}
			isTrue = false;
			this.notify();
		}

		public synchronized void main(int i) {
			while (isTrue) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			for (int j = 0; j < 50; j++) {
				System.out.println("this is mainthread:" + j + "loop of:" + i);
			}
			isTrue = true;
			this.notify();
		}
	}

}
